package com.study.security.core.validate.code;

import com.study.security.core.properties.SecurityProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.social.connect.web.HttpSessionSessionStrategy;
import org.springframework.social.connect.web.SessionStrategy;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.ServletWebRequest;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

@RestController
public class ValidateCodeController {

    public static final String SESSION_KEY = "SESSION_KEY_IMAGE_CODE";
    public static final String SESSION_KEY_SMS = "SESSION_KEY_SMS_CODE";

    private SessionStrategy sessionStrategy = new HttpSessionSessionStrategy();

    @Autowired
    private ValidateCodeGenerator imageCodeGenerator;

    @Autowired
    private ValidateCodeGenerator smsCodeGenerator;
    @Autowired
    private SmsCodeSender smsCodeSender;

    @GetMapping("/code/image")
    public void createCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //1.创建图形验证码对象
        ImageCode imageCode = (ImageCode) imageCodeGenerator.generate(new ServletWebRequest(request));
        //2.将图形验证码放到session中
        //因为ImageCode中的BufferedImage没法实现序列化，所以要将ImageCode转成ValidateCode
        ValidateCode validateCode = new ValidateCode(imageCode.getCode(),imageCode.getExpireTime());
        sessionStrategy.setAttribute(new ServletWebRequest(request), SESSION_KEY, validateCode);
        //3.将图形验证码写进返回结果中，并在前端显示
        ImageIO.write(imageCode.getImage(), "JPEG", response.getOutputStream());
    }

    @GetMapping("/code/sms")
    public void sendSms(HttpServletRequest request, HttpServletResponse response) throws ServletRequestBindingException {
        //1.生成一个验证码对象
        ValidateCode smsCode = smsCodeGenerator.generate(new ServletWebRequest(request));
        //2.将验证码对象放到session中
        sessionStrategy.setAttribute(new ServletWebRequest(request), SESSION_KEY_SMS, smsCode);
        //3.调用短信发送功能
        String mobile = ServletRequestUtils.getStringParameter(request, "mobile");
        smsCodeSender.send(mobile, smsCode.getCode());
    }

}
